package com.lynn.common.utils.encrypt;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * DESC: MD5加密工具类
 * TIME:2019-06-21
 */
public class MD5Util {

    private MD5Util() {
        throw new UnsupportedOperationException("u can't fuck me...");
    }


    /**
     * 不带Key 的加密
     * 多用于加密登录密码等
     *
     * @param pstr
     * @return
     */
    public static String toMD5NoKey(String pstr) {
        return toMD5("", pstr);
    }

    /**
     * 将字符串进行MD5加密
     *
     * @param secretKey 密钥
     * @param pstr      被加密的字符串
     * @return
     */
    public static String toMD5(String secretKey, String pstr) {
        //加密
        pstr = secretKey + pstr;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            MessageDigest md5Temp = MessageDigest.getInstance("MD5");
            md5Temp.update(pstr.getBytes("UTF8"));
            byte[] md = md5Temp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).toLowerCase();
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 对字符串进行MD5加密 32位大写
     *
     * @param src 加密对象
     * @return 返回一个32位大写的字符串，返回“”表示加密异常
     */
    public static String md5_32(String src) {
        if (TextUtils.isEmpty(src)) {
            src = "";
        }
        String result = "";
        try {
            //获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //使用指定的字节更新摘要
            md.update(src.getBytes());
            //获得密文
            byte b[] = md.digest();
            //转化成十六进制的字符串形式
            int i;
            StringBuilder buf = new StringBuilder();
            for (byte aB : b) {
                i = aB;
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

}
